package com.ktwlsoft.archivemanage.domain.business.businessService.businessInspectTem;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.ktwlsoft.archivemanage.config.exception.ResultException;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.OperationRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.businessInspectTem.BusinessInspectTemRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.businessInspectTem.InspectTemSubjectItemRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.businessInspectTem.InspectTemSubjectRepositoryService;
import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.entity.OperationLog;
import com.ktwlsoft.archivemanage.domain.dao.entity.businessInspectTem.BusinessInspectTem;
import com.ktwlsoft.archivemanage.domain.dao.entity.businessInspectTem.InspectTemSubject;
import com.ktwlsoft.archivemanage.domain.dao.entity.businessInspectTem.InspectTemSubjectItem;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.businessInspectTem.BusinessInspectTemSaveRequest;
import com.ktwlsoft.archivemanage.payload.businessInspectTem.BusinessInspectTemUpdateRequest;
import com.ktwlsoft.archivemanage.payload.operationLog.SaveLogRequest;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import com.ktwlsoft.archivemanage.service.utils.DateUtils;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 业务检查模板
 *
 * @author zhuhe on 2019/11/6 16:19
 * @version 1.0
 */
@Component
public class BusinessInspectTemService {

    /**业务检查模板*/
    private final BusinessInspectTemRepositoryService repositoryService;
    
    /**指导模板题目*/
    private final InspectTemSubjectRepositoryService subjectRepositoryService;
    
    /**指导模板题目选项*/
    private final InspectTemSubjectItemRepositoryService itemRepositoryService;

    public BusinessInspectTemService(BusinessInspectTemRepositoryService repositoryService, InspectTemSubjectRepositoryService subjectRepositoryService, InspectTemSubjectItemRepositoryService itemRepositoryService) {
        this.repositoryService = repositoryService;
        this.subjectRepositoryService = subjectRepositoryService;
        this.itemRepositoryService = itemRepositoryService;
    }

    /**
      * 业务检查模板新增 on 2019/11/6 16:55
      *
      * @param request request
      * @return Result<?>
      */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> save(BusinessInspectTemSaveRequest request){
        Account account = UserPrincipal.getCurrentUser();
        if(account == null){
            account = new Account();
        }
        BusinessInspectTem businessInspectTem = new BusinessInspectTem();
        BeanUtils.copyProperties(request, businessInspectTem);
        businessInspectTem.setCreator(account.getRealName());
        businessInspectTem.setCreatorId(account.getId());
        businessInspectTem.setUpdateId(account.getId());
        businessInspectTem.setUpdate(account.getRealName());
        //模板题目
        List<InspectTemSubject> subjectList = Lists.newArrayList();
        //模板题目选项
        List<InspectTemSubjectItem> items = Lists.newArrayList();
        if(request.getSubjectList() != null && request.getSubjectList().size() > 0){
            request.getSubjectList().forEach(value ->{
                InspectTemSubject subject = new InspectTemSubject();
                BeanUtils.copyProperties(value,subject);
                subject.setCreator(businessInspectTem.getCreator());
                subject.setCreatorId(businessInspectTem.getCreatorId());
                subject.setTemId(businessInspectTem.getId());
                subjectList.add(subject);
                //模板题目选项
                if(value.getItemList() != null && value.getItemList().size() > 0){
                    value.getItemList().forEach(itemValue ->{
                        InspectTemSubjectItem item = new InspectTemSubjectItem();
                        BeanUtils.copyProperties(itemValue,item);
                        item.setCreator(subject.getCreator());
                        item.setCreatorId(subject.getCreatorId());
                        item.setSubjectId(subject.getId());
                        items.add(item);
                    });
                }
            });
        }
        try {
            repositoryService.insert(businessInspectTem);
            if(subjectList.size() > 0){
                subjectRepositoryService.manyInsert(subjectList);
            }
            if(items.size() > 0){
                itemRepositoryService.manyInsert(items);
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new ResultException(ResultType.SAVING_ERROR.getReason(),ResultType.SAVING_ERROR);
        }
        return Result.ok(businessInspectTem.getId());
    }

    /**
      * 业务检查模板修改 on 2019/11/7 9:10
      *
      * @param request request
      * @return Result<?>
      */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> modify(BusinessInspectTemUpdateRequest request){
        Account account = UserPrincipal.getCurrentUser();
        if(account == null){
            account = new Account();
        }
        BusinessInspectTem businessInspectTem = new BusinessInspectTem();
        BeanUtils.copyProperties(request, businessInspectTem);
        businessInspectTem.setUpdateId(account.getId());
        businessInspectTem.setUpdate(account.getRealName());
        //模板题目新增
        List<InspectTemSubject> subjectSave = Lists.newArrayList();
        //模板题目删除
        List<Long> subjectDelete = Lists.newArrayList();
        //模板题目修改
        List<InspectTemSubject> subjectModify = Lists.newArrayList();
        //模板题目选项新增
        List<InspectTemSubjectItem> itemSave = Lists.newArrayList();
        //模板题目选项删除
        List<Long> itemDelete = Lists.newArrayList();
        //模板题目选项修改
        List<InspectTemSubjectItem> itemModify = Lists.newArrayList();
        if(request.getSubjectList() != null && request.getSubjectList().size() > 0){
            //模板题目
            request.getSubjectList().forEach(value ->{
                InspectTemSubject subject = new InspectTemSubject();
                BeanUtils.copyProperties(value,subject);
                if(value.getId() == null && value.getType().equals(1)){
                    //新增
                    subject.setCreator(businessInspectTem.getCreator());
                    subject.setCreatorId(businessInspectTem.getCreatorId());
                    subject.setTemId(businessInspectTem.getId());
                    subject.setId(SnowFlake.getNextId());
                    subjectSave.add(subject);
                }else if(value.getId() != null && value.getType().equals(2)){
                    //修改
                    subjectModify.add(subject);
                }else if(value.getId() != null && value.getType().equals(3)){
                    //删除
                    subjectDelete.add(subject.getId());
                }
                if(value.getItemList() != null && value.getItemList().size() > 0){
                    //模板题目选项
                    value.getItemList().forEach(itemValue ->{
                        InspectTemSubjectItem item = new InspectTemSubjectItem();
                        BeanUtils.copyProperties(itemValue,item);
                        if(itemValue.getId() == null && itemValue.getType().equals(1)){
                            //新增
                            item.setCreator(subject.getCreator());
                            item.setCreatorId(subject.getCreatorId());
                            item.setSubjectId(subject.getId());
                            item.setId(SnowFlake.getNextId());
                            itemSave.add(item);
                        }else if(itemValue.getId() != null && itemValue.getType().equals(2)){
                            //修改
                            itemModify.add(item);
                        }else if(itemValue.getId() != null && itemValue.getType().equals(3)){
                            //删除
                            itemDelete.add(item.getId());
                        }
                    });
                }
            });
        }
        try {
            //修改业务检查模板
            repositoryService.update(businessInspectTem);
            if(subjectSave.size() > 0){
                //新增指导模板题目
                subjectRepositoryService.manyInsert(subjectSave);
            }
            if(subjectModify.size() > 0){
                //编辑指导模板题目
                for(InspectTemSubject subject:subjectModify){
                    subjectRepositoryService.update(subject);
                }
            }
            if(subjectDelete.size() > 0){
                //删除指导模板题目
                subjectRepositoryService.deleteByIds(subjectDelete);
            }
            if(itemSave.size() > 0){
                //新增指导模板题目选项
                itemRepositoryService.manyInsert(itemSave);
            }
            if(itemModify.size() > 0){
                //修改指导模板题目选项
                for(InspectTemSubjectItem item:itemModify){
                    itemRepositoryService.update(item);
                }
            }
            if(itemDelete.size() > 0){
                //删除指导模板题目选项
                itemRepositoryService.deleteByIds(itemDelete);
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new ResultException(ResultType.UPDATE_ERROR.getReason(),ResultType.UPDATE_ERROR);
        }
        return Result.ok(request.getName());
    }

    /**
      * 业务检查模板删除 on 2019/11/7 10:29
      *
      * @param id id
      * @return Result<?>
      */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteById(Long id){
        if(id == null || id <= 0){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        BusinessInspectTem businessInspectTem = repositoryService.getById(id);
        if(businessInspectTem == null){
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        InspectTemSubject subject = new InspectTemSubject();
        subject.setId(null);
        subject.setCreator(null);
        subject.setCreatorId(null);
        subject.setCreatedAt(null);
        subject.setUpdateAt(null);
        subject.setTemId(businessInspectTem.getId());
        List<InspectTemSubject> subjectList = subjectRepositoryService.findList(subject);
        List<Long> subLongs = Lists.newArrayList();
        List<Long> itemLongs = Lists.newArrayList();
        if(subjectList != null && subjectList.size() > 0){
            subjectList.forEach(value ->{
                subLongs.add(value.getId());
                InspectTemSubjectItem item = new InspectTemSubjectItem();
                item.setId(null);
                item.setCreator(null);
                item.setCreatorId(null);
                item.setCreatedAt(null);
                item.setUpdateAt(null);
                item.setSubjectId(value.getId());
                List<InspectTemSubjectItem> items = itemRepositoryService.findList(item);
                if(items != null && items.size() > 0){
                    items.forEach(itemValue ->{
                        itemLongs.add(itemValue.getId());
                    });
                }
            });
        }
        try {
            repositoryService.deleteById(id);
            if(subLongs.size() >0){
                subjectRepositoryService.deleteByIds(subLongs);
            }
            if(itemLongs.size() > 0){
                itemRepositoryService.deleteByIds(itemLongs);
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new ResultException(ResultType.DELETE_ERROR.getReason(),ResultType.DELETE_ERROR);
        }
        return Result.ok(businessInspectTem.getName());
    }

    /**
      * 业务检查模板启用禁用 on 2019/11/7 11:12
      *
      * @param id id
      * @return Result<?>
      */
    public Result<?> enable(Long id){
        if(id == null || id <= 0){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        BusinessInspectTem businessInspectTem = repositoryService.getById(id);
        if(businessInspectTem == null){
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        Account account = UserPrincipal.getCurrentUser();
        if(account == null){
            account = new Account();
        }
        businessInspectTem.setUpdateId(account.getId());
        businessInspectTem.setUpdate(account.getRealName());
        businessInspectTem.setUpdateAt(new Date());
        if(businessInspectTem.getEnable().equals(1)) {
            businessInspectTem.setEnable(0);
        }else{
            businessInspectTem.setEnable(1);
        }
        try {
            repositoryService.update(businessInspectTem);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(null, ResultType.UPDATE_ERROR);
        }
        if(businessInspectTem.getEnable() == 1){
            saveLog(OperationLog.OperationType.ENABLE,"启用模板《" + businessInspectTem.getName() + "》");
        }else{
            saveLog(OperationLog.OperationType.DISABLE,"禁用模板《" + businessInspectTem.getName() + "》");
        }
        return Result.ok(businessInspectTem.getName());
    }

    /**
      * 通过id获取详情 on 2019/11/7 11:45
      *
      * @param id id
      * @return Result<?>
      */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> getByid(Long id){
        if(id == null || id <= 0){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        BusinessInspectTem businessInspectTem = repositoryService.getById(id);
        if(businessInspectTem == null){
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        InspectTemSubject subject = new InspectTemSubject();
        subject.setId(null);
        subject.setCreator(null);
        subject.setCreatorId(null);
        subject.setCreatedAt(null);
        subject.setUpdateAt(null);
        subject.setTemId(businessInspectTem.getId());
        businessInspectTem.setSubjectList(subjectRepositoryService.findList(subject));
        if(businessInspectTem.getSubjectList() != null && businessInspectTem.getSubjectList().size() > 0){
            businessInspectTem.getSubjectList().forEach(value ->{
                InspectTemSubjectItem item = new InspectTemSubjectItem();
                item.setId(null);
                item.setCreator(null);
                item.setCreatorId(null);
                item.setCreatedAt(null);
                item.setUpdateAt(null);
                item.setSubjectId(value.getId());
                value.setItemList(itemRepositoryService.findList(item));
            });
        }
        return Result.ok(businessInspectTem);
    }

    /**
      * 业务检查模板列表 on 2019/11/7 12:24
      *
      * @param operationStartTime 操作开始时间
      * @param operationEndTime 操作结束时间
      * @param enable 状态
      * @param keyWords 关键字
      * @return Result<?>
      */
    public Result<?> findPage(int pn,int pageSize,String operationStartTime,String operationEndTime,Integer enable,String keyWords,String inspectType,String field,String order){
        JSONObject object = new JSONObject();
        if(operationStartTime != null && !"".equals(operationStartTime.trim())) {
            object.put("operationStartTime", DateUtils.dayMinTime(operationStartTime.trim()));
        }
        if(operationEndTime != null && !"".equals(operationEndTime.trim())){
            object.put("operationEndTime",DateUtils.dayMaxTime(operationEndTime.trim()));
        }
        if(enable != null){
            object.put("enable",enable);
        }
        if(keyWords != null && !"".equals(keyWords.trim())){
            object.put("keyWords",keyWords.trim());
        }
        if(inspectType != null && !"".equals(inspectType.trim())){
            object.put("inspectType",inspectType.trim());
        }
        if(field != null && !"".equals(field)) {
            object.put("field", field.replaceAll("[A-Z]", "_$0").toLowerCase());
        }
        if(order != null && !"".equals(order)) {
            object.put("order", "ascend".equals(order) ? "ASC" : "DESC");
        }
        PageInfo<BusinessInspectTem> pageInfo = repositoryService.findJsonPage(pn,pageSize,object);
        return Result.ok(pageInfo);
    }

    /**
     * 新增日志 on 2019/11/14 10:37
     *
     * @param operationType 操作类型
     * @param description 描述
     */
    private void saveLog(OperationLog.OperationType operationType, String description){
        OperationRepositoryService.saveLog(new SaveLogRequest(
                operationType,
                description,
                "业务检查模板",
                OperationLog.BusinessType.BUSINESS
        ));
    }
}